package com.jshongli.myapplication.inspect;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.google.gson.Gson;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.MyCallback;
import com.jshongli.myapplication.common.callback.UpdateCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.SuccessDialogUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.model.base.Update;
import com.jshongli.myapplication.model.inspect.PointBean;
import com.jshongli.myapplication.model.user.UserBean;
import com.jshongli.myapplication.model.user.UserInfo;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

public class DistributeActivity extends BaseActivity {

    @BindView(R.id.spinner)
    Spinner spinner;

    private ArrayAdapter<String> point_adapter;
    List<UserBean.DATA> point_List = new ArrayList<>();
    List<String> PointArray = new ArrayList ();
    private String selectchild = "";
    private String selectchildname = "";
    @Override
    protected int getLayoutId() {
        return R.layout.activity_distribute;
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initView() {
        super.initView();

        mToolbar.setTitle("任务派发");
        initToolbarBack(mToolbar);


        initPD();

        getChildren();

    }

    //region initPD
    private ProgressDialog pd;

    private void initPD() {
        pd = new ProgressDialog(mContext);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.setMessage(getString(R.string.waiting));
    }
    //endregion

    private void getChildren()
    {
        pd.show();
        Map<String, String> map = new HashMap<>();
        OkHttpUtils.get().url(URLUtils.URLNoToken("manageAPI/sysUser/getChildren")).addHeader("Authorization", AccountManager.getToken()).params(map).tag(this)
                .build().execute(new MyCallback<UserBean>(mContext) {


            @Override
            public void onSuccess(UserBean response) {
                pd.dismiss();
                if(response.success)
                {
                    point_List.clear();
                    point_List.addAll(response.data);
                    PointArray.clear();
                    for(UserBean.DATA item:point_List)
                    {
                        PointArray.add("【"+item.orgName+"】"+item.realName);
                    }
                    if(PointArray.size()>0)
                    {
                        UserBean.DATA item = point_List.get(0);
                        selectchild = String.valueOf(item.id);
                        selectchildname = "【"+item.orgName+"】"+item.realName;
                    }

                    //适配器
                    point_adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, PointArray);
                    //设置样式
                    point_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //加载适配器
                    spinner.setAdapter(point_adapter);
                    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view,
                                                   int position, long id) {
                            String str = parent.getItemAtPosition(position).toString();
                            selectchildname = str;
                            UserBean.DATA item = point_List.get(position);
                            selectchild = String.valueOf(item.id);
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            // TODO Auto-generated method stub
                        }
                    });


                }else {
                    ToastUtils.show(mContext, "数据解析出错");
                }
            }

            @Override
            public void onFail(UserBean response) {
                super.onFail(response);
                ToastUtils.show(mContext, "获取用户失败，请重新进入");
            }
        });

    }

    private void upload() {

        pd.show();

        String url = URLUtils.URLNoToken("manageAPI/bizEvent/distribute");

        Map<String, String> map = new HashMap<String, String>();
        map.put("id", getIntent().getStringExtra("id"));
        map.put("userId", selectchild);

        Gson gson = new Gson();
        final String s = gson.toJson(map);

        OkHttpUtils
                .postString()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(s)
                .build()
                .execute(new UpdateCallback<Update>(mContext) {

                    @Override
                    public void onSuccess(Update response) {

                        pd.dismiss();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                Intent intent = new Intent();
                                intent.putExtra("username",selectchildname);
                                setResult(5986, intent);

                                finish();
                            }
                        }, 1000);
                    }

                    @Override
                    public void onUpdating() {

                    }

                    @Override
                    public void onUpdateFailed() {
                        pd.dismiss();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                        pd.dismiss();
                    }
                });
    }

    @OnClick({R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                upload();
                break;

        }
    }


}